<template>
    <div class="uploadFilesList-div" :style="{height: heigth?heigth + 'px':'auto',}">
        <!-- <a-form layout="inline" style="display: flex;justify-content: flex-start;">
            <a-form-item class="vxe-table-box-w" v-if="config.isUpload">
                <a-upload :showUploadList="false" :beforeUpload="beforeUpload" action="" @change="uploadClick">
                    <a-button class="blue-btn" icon="upload">上传附件</a-button>
                </a-upload>
            </a-form-item>
            <a-form-item class="vxe-table-box-w" v-if="config.isAttachmentView">
                <a-button class="blue-btn" @click="filesVisible = true">常用附件模板查看</a-button>
            </a-form-item>
        </a-form> -->
        <div style="text-align:left;">
            <a-upload :showUploadList="false" :beforeUpload="beforeUpload" action="" @change="uploadClick">
                <a-button class="blue-btn" icon="upload" v-if="config.isUpload">上传附件</a-button>
            </a-upload>
            <a-button class="blue-btn" v-if="config.isAttachmentView" @click="filesVisible = true" style="margin-left: 10px;">常用附件模板查看</a-button>
        </div>
        <a-list v-if="config.handleIconStyle == true" item-layout="horizontal" :data-source="filesListData" class="handleBtn-style" :style="{height: heigth?(heigth - 40) + 'px':'auto',}">
            <a-list-item slot="renderItem" slot-scope="item, index">
                <a-list-item-meta>
                    <a @click="openFiles(item)" slot="title" href="#" class="uploadFilesList-mc">
                        {{ item.fmc }}
                        <a-icon @click.stop="openFiles(item)" type="eye" style="color:green;font-size:18px;margin:0px 5px 0px 10px;"/>
                        <a-icon @click.stop="downloadFiles(item)" type="download" style="color:deepskyblue;font-size:18px;margin:0px 5px;"/>
                        <a-icon @click.stop="deleteFiles(item.id)" v-if="config.isUpload" type="delete" style="color:red;font-size:18px;margin:0px 5px;"/>
                    </a>
                </a-list-item-meta>
            </a-list-item>
        </a-list>
        <vxe-table
            v-else-if="config.handleTableStyle == true"
            stripe
            border
            show-overflow
            :data="filesListData"
            class="transferRecords-table">
            <vxe-column type="seq" title="序号" width="70" align="center"></vxe-column>
            <vxe-column field="fmc" title="文件名" align="center">
                <template v-slot="{ row }">
                    <a @click="openFiles(row)">{{ row.fmc }}</a>
                </template>
            </vxe-column>
            <vxe-column field="fscr" title="上传人" width="108" align="center">
                <template v-slot="{ row }">
                    <span v-if="row.fscr.length == 2">
                        <span v-for="(trem,tI) in row.fscr.split('')" :key="tI" >
                            {{trem}}
                            <span v-if="tI+1 !== row.fscr.split('').length">&ensp;</span>
                        </span>
                    </span>
                    <span v-else>{{ row.fscr }}</span>
                </template>
            </vxe-column>
            <vxe-column field="fscsj" title="上传时间" width="300" align="center"></vxe-column>
            <vxe-column field="d" title="操作" width="100" align="center">
                <template v-slot="{ row }">
                    <a @click="downloadFiles(row)">下载</a>
                </template>
            </vxe-column>
        </vxe-table>
        <a-list v-else item-layout="horizontal" :data-source="filesListData">
            <a-list-item slot="renderItem" slot-scope="item, index">
                <a-list-item-meta>
                    <a @click="openFiles(item)" slot="title" href="#" class="uploadFilesList-mc">{{ item.fmc }}</a>
                </a-list-item-meta>
                <a-button style="margin-right: 10px;" class="green-btn" @click="openFiles(item)" icon="eye">预览</a-button>
                <a-button style="margin-right: 10px;" class="green-l-btn" @click="downloadFiles(item)" icon="download">下载附件</a-button>
                <a-button
                    v-if="config.isUpload"
                    class="red-btn"
                    style="margin-right: 10px;"
                    @click="deleteFiles(item.id)" icon="delete">
                    删除附件
                </a-button>
                <!-- <a-button style="margin-right: 10px;" class="blue-btn" @click="onlineEditing(item)" icon="edit">在线编辑</a-button> -->
            </a-list-item>
        </a-list>
        <a-modal
            title="常用附件模板查看"
            :visible="filesVisible"
            @ok="filesVisible = false"
            @cancel="filesVisible = false"
            :footer="null"
            width="60%"
            :dialog-style="{ top: '0px' }"
        >
            <attachmentView></attachmentView>
        </a-modal>
        <a-modal
            title="附件预览"
            :visible="visibleFiles"
            @ok="visibleFiles = false"
            @cancel="visibleFiles = false"
            :footer="null"
            width="80%"
            :height="(windowInnerHeight -150 )+'px'"
            :dialog-style="{ top: '10px' }"
        >
            <iframe
                v-if="iframeSrc"
                :key="iframeKey"
                :src="iframeSrc"
                ref="iframeServerEditingRef"
                scrolling="auto"
                width="100%"
                :height="(windowInnerHeight -150 )+'px'"
                style="border: 0;"
                class="iframe-view"
            ></iframe>
            <span v-else>当前文件发生错误，请刷新！</span>
        </a-modal>
        <a-modal
            title="在线编辑"
            :visible="onlineEditVisible"
            @ok="onlineEditVisible = false"
            @cancel="onlineEditVisible = false"
            :footer="null"
            width="100%"
            :dialog-style="{ top: '0px' }"
            wrapClassName="full-modal"
        >
            <a-spin size="large" :spinning="spinning">
                <div style="margin-bottom: 15px;">
                    <a-button style="margin-right: 15px;" class="blue-btn" type="primary" @click="refreshClick">刷新</a-button>
                    <a-button style="margin-right: 15px;" class="blue-btn" type="primary" @click="reEditClick">重新编辑</a-button>
                    <a-button style="margin-right: 15px;" class="blue-btn" type="primary" @click="saveClick">保存</a-button>
                    <a-button style="margin-right: 15px;" class="blue-btn" type="primary" @click="closeClick">关闭</a-button>
                </div>
                <div v-if="onlineEditVisible">
                    <iframe
                        v-if="iframeSrc"
                        :key="iframeKey"
                        :src="iframeSrc"
                        ref="iframeServerEditingRef"
                        scrolling="auto"
                        width="100%"
                        :height="(windowInnerHeight -170 )+'px'"
                        style="border: 0;"
                    ></iframe>
                    <span v-else>当前文件发生错误，请刷新！</span>
                </div>
            </a-spin>
        </a-modal>
    </div>
</template>
<script>
import {
    fjupload,
    fjAdd,
    openFile,
    downLoadOa,
    fjlist,
    deleleMinioFile,
} from './service/index'
import { axios } from '@/utils/request'
import blobType from '@/common/blobType'
import attachmentView from '../AttachmentTemplate/index'
import YchConstant from "@/api/YchConstant";
export default {
    props: {
        config:{
            type:Object,
            default:()=>{
                return {}
            },
            required:false,
        },
        filesFormState:{
            type:Object,
            default:()=>{
                return {}
            },
            required:false,
        },
        heigth:{
            type:Number,
            default:()=>{
                return null
            },
            required:false,
        },
    },
    components: {
        attachmentView,
    },
    data() {
        return {
            filesListData: [],
            filesVisible: false,
            visibleFiles: false,
            onlineEditVisible: false,
            iframeSrc:'',
            iframeKey:null,
            windowInnerHeight:window.innerHeight,
            spinning: false,
        }
    },
    mounted() {
        //console.log(this.filesFormState)
        if(this.filesFormState.id){
            this.getFilesList()
        }
    },
    methods: {
        getData(){},
        beforeUpload(e){
            return false
        },
        getFilesList(){
            fjlist({foaid:this.filesFormState.id}).then(res => {
                this.filesListData = []
                this.filesListData = res.result.records
            })
        },
        // 上传附件
        async uploadClick({file}){
            // //console.log(file)
            //console.log(this.filesFormState)
            if(!this.filesFormState.id){
                let data = {}
                data = {
                    ...this.filesFormState
                }
                const res = await axios({
                        url: this.config.fjAddApi,
                        method:'post' ,
                        data: {
                            id: '',
                            ...data,
                        },
                        url_1:'',
                        url_2:'outside',
                    })
                if (res.success) {
                    let map = res.result.oaMap?res.result.oaMap:res.result.nkMap
                    this.filesFormState.id = map.id
                    this.uploadClicka(file,map.id)
                    this.$emit('emitFormid',res.result)
                }
            } else {
                this.uploadClicka(file,this.filesFormState.id)
            }
        },
        uploadClicka(file,id){
            //console.log(file)
            var that = this
            if(typeof file.uid !== 'undefined') {
            const fileData = new FormData();
            fileData.append("file",file);
            fileData.append("oaid",id);
            //console.log(fileData)
            fjupload(fileData).then(res => {
                //console.log('fileData',res)
                if (res.success) {
                that.$message.success(res.message)
                that.getFilesList()
                } else {
                that.$message.warning(res.message)
                }
            })
            }
        },
        // 预览
        openFiles(item){
            if((item.fwjlx.indexOf('doc') !== -1) || (item.fwjlx.indexOf('docx') !== -1)){
                openFile({id:item.id}).then(res => {
                    if(!res.success){
                        this.$message.warning('当前附件类型不支持预览,请下载查看')
                    } else {
                        if(res.result.wordUrl == ''){
                            this.$message.warning('当前附件预览失败,请下载查看')
                            return
                        }
                        this.iframeSrc = res.result.wordUrl
                        this.iframeKey = Date.now()
                        this.visibleFiles = true
                    }
                })
            } else {
                this.iframeSrc = bootConfig[process.env.NODE_ENV].locality_ApI2+YchConstant.SPZX_OA+'/oaFjzyk/downLoadOa?id='+item.id
                this.iframeKey = Date.now()
                this.visibleFiles = true
            }
        },
        // 下载附件
        downloadFiles(val){
          //console.log('下载',val)
          var that = this
          var fileName = val.fmc
          downLoadOa({id:val.id}).then((data) => {
            // //console.log(data)
              if (!data) {
                  that.$message.warning('文件下载失败')
                  return
              }
              let url = window.URL.createObjectURL(new Blob([data], { type: blobType.type[blobType.suffix.indexOf(val.fwjlx)] }))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName)
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
              // this.vxModal.visabled = false;
          })
        },
        // 删除附件
        deleteFiles(idd){
            var that = this
            that.$confirm({
                title: '您确定要删除当前附件吗?',
                onOk() {
                    deleleMinioFile({id:idd}).then(res => {
                        if(res.code == 200){
                            that.$message.success('删除成功')
                            that.getFilesList()
                        } else {
                            that.$message.warning(res.message)
                        }
                    })
                },
                onCancel() {
                    //console.log('Cancel');
                },
            });
        },
        // 在线编辑
        onlineEditing(item,isMess){
            //console.log('item:',item)
            if(isMess){
                this.refreshFileLoading = true
            }
            if((item.fwjlx.indexOf('doc') !== -1) || (item.fwjlx.indexOf('docx') !== -1)){
                openFile({id:item.id}).then(res => {
                    if(res.success){
                        this.iframeKey = Date.now()
                        this.iframeSrc = res.result.wordUrl
                        this.onlineEditVisible = true
                        if(isMess){
                            this.$message.success('刷新成功！')
                        }
                    } else {
                        this.iframeSrc = null
                    }
                })
            } else {
                this.$message.warning('当前附件类型不支持在线编辑')
            }
        },
        cancelLoading(){
            let timer = setInterval((val)=>{
                this.serverEditingSpinning = false
                clearInterval(timer);
            },500)

        },
        refreshClick(){
            this.serverEditingSpinning = true
            this.iframeKey = Date.now()
            this.cancelLoading()
        },

        reEditClick(){
            this.serverEditingSpinning = true
            this.cancelLoading()
            // againEditPdfOnlineFile({id:this.rowObj.id}).then(res=>{
            //     if(res.code == 200){
            //         this.$emit('refreshChange')
            //         this.isPdf = false
            //         this.openFileClick(this.rowObj)
            //         this.iframeKey = Date.now()
            //     }else{
            //         this.$message.warning(res.message)
            //     }
            //     this.cancelLoading()
            // })
        },
        saveClick(){
            this.serverEditingSpinning = true
            this.cancelLoading()
        },
        closeClick(){
            this.onlineEditVisible = false
            // if(this.rowObj.fwjlx == '.doc' ||this.rowObj.fwjlx == '.docx'){
            // }else{
            //     this.onlineEditVisible = false
            // }
        },
    },
}
</script>
<style lang="less">
.uploadFilesList-div {
    white-space: normal;
    .ant-list-empty-text {
        padding: 0px !important;
    }
    .ant-empty-normal {
        margin: 0px !important;
    }
    .handleBtn-style {
        overflow-y: auto;
        .ant-list-item {
            display: inline-block;
            margin-right: 15px;
            border-bottom: none;
        }
    }
}
.uploadFilesList-mc {
    color: #2F54EB !important;
    padding: 5px 10px;
    border-radius: 15px;
    border: 1px solid #d9d9d9;
}
.iframe-view {
    html {
        width: 80%;
        background-color: #2F54EB;
    }
    img {
        width: 100%;
        height: 100%;
    }
}
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
}
</style>
